﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using CoreShop.Repository;
using SqlSugar;
namespace CoreShop.Services
{
    /// <summary>
    /// 接口实现
    /// </summary>
    public class corecmschgpriceServices : Repository<corecmschgprice>, IcorecmschgpriceServices
    {
        public bool InsertAsync(corecmschgprice entity)
        {
            return base.Change<corecmschgprice>().Insert(entity);
        }
        public bool InsertOrUpdate(List<corecmschgprice> entity)
        {
            return base.InsertOrUpdate(entity);
        }

        #region 搜索调价单
        public decimal GetChgPrice(long id,decimal sourcePrice)
        {
            var where = Expressionable.Create<corecmschgprice>();
            where = where.And(p => p.pdtSpuSpecId == id);
            where = where.And(p => p.status == (int)GlobalEnumVars.ChgpriceStatus.Check || p.status == (int)GlobalEnumVars.ChgpriceStatus.Effective);
            where = where.And(p => p.effectiveDate <= DateTime.Now && (p.expiringDate >= DateTime.Now || p.expiringDate == null));
            var food = base.AsQueryable().WhereIF(true, where.ToExpression()).OrderBy(a => a.chgpriceLineId,OrderByType.Desc).With(SqlWith.NoLock).ToList().FirstOrDefault();
            if (food != null) return food.newSalePrice;
            return sourcePrice;
        }

        public List<corecmschgprice> GetChgPriceList(List<long> ids)
        {
            var where = Expressionable.Create<corecmschgprice>();
            where = where.And(p => ids.Contains(p.pdtSpuSpecId));
            where = where.And(p => p.status == (int)GlobalEnumVars.ChgpriceStatus.Check || p.status == (int)GlobalEnumVars.ChgpriceStatus.Effective);
            where = where.And(p => p.effectiveDate <= DateTime.Now && (p.expiringDate >= DateTime.Now || p.expiringDate == null));

            var listGroup = base.AsQueryable().WhereIF(true, where.ToExpression())
                  .GroupBy((a) => new { a.pdtSpuSpecId })
                  .Select((a) => new ChgPriceDto
                  {
                      pdtSpuSpecId = a.pdtSpuSpecId,
                      chgpriceLineId = SqlFunc.AggregateMax(a.chgpriceLineId)
                  }).With(SqlWith.NoLock).ToList();

            if (listGroup.Count == 0) return null;
            var spuIds = listGroup.Select(f => f.chgpriceLineId).ToList();
            var list = base.AsQueryable().Where(p=>spuIds.Contains(p.chgpriceLineId)).With(SqlWith.NoLock).ToList();

            return list;
        }
        #endregion

        /// <summary>
        /// 重写删除指定ID的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteByIdAsync(long id)
        {
            return base.Change<corecmschgprice>().DeleteById(id);
        }

        /// <summary>
        /// 重写删除指定ID集合的数据(批量删除)
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool DeleteByIdsAsync(int[] ids)
        {
            bool returnKey = true;
            foreach (int id in ids)
            {
                returnKey = base.Change<corecmschgprice>().DeleteById(id);
            }
            return returnKey;
        }
        #region 获取缓存的所有数据==========================================================

        /// <summary>
        /// 获取缓存的所有数据
        /// </summary>
        /// <returns></returns>
        public List<corecmschgprice> GetCaChe()
        {
            return base.GetList();
        }

        #endregion
    
        public List<corecmschgprice> QueryAsync(long id)
        {
            List<corecmschgprice> list = new List<corecmschgprice>();
            var where = Expressionable.Create<corecmschgprice>();
            if (id > 0)
            {
                where = where.And(a => a.chgpriceLineId == id);
            }
            list = base.AsQueryable().WhereIF(true, where.ToExpression()).OrderBy(a => a.chgpriceLineId).ToList();
            return list;
        }

        #region 根据条件查询分页数据
        /// <summary>
        /// 根据条件查询分页数据
        /// </summary>
        /// <param name="count"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sName"></param>
        /// <returns></returns>
        public List<corecmschgprice> QueryPageAsync(ref int count, int? pageIndex, int? pageSize, string sName, DateTime sDate)
        {
            var where = Expressionable.Create<corecmschgprice, corecmsfoodspec>();
            where = where.And((f, s) => f.expiringDate >= sDate && f.effectiveDate <= sDate);
            
            if (!string.IsNullOrEmpty(sName))
                where = where.And((f, s) => s.name.Contains(sName) || s.number.Contains(sName) || s.code.Contains(sName));

            List<corecmschgprice> lst = base.AsQueryable().LeftJoin<corecmsfoodspec>((f, s) => f.pdtSpuSpecId == s.id)
                .WhereIF(true, where.ToExpression()).Select((f, s) => new corecmschgprice
                {
                    chgpriceLineId = f.chgpriceLineId,
                    pdtSpuSpecId = f.pdtSpuSpecId,
                    number = s.number,
                    name = s.name,
                    code = s.code,
                    specName = s.specName,
                    specUnitName = s.specUnitName,
                    posPrice = s.posPrice,
                    vipPrice = s.vipPrice,
                    newSalePrice =f.newSalePrice,
                    billNo = f.billNo,
                    effectiveDate = f.effectiveDate,
                    expiringDate = f.expiringDate
                }).OrderBy(f => f.chgpriceLineId, OrderByType.Desc).ToPageList((int)pageIndex, (int)pageSize, ref count).ToList();                       

            return lst;
        }
        #endregion

    }
}
